#ifndef IMAGE_HPP
#define IMAGE_HPP

#include <SDL2/SDL_image.h>
#include <SDL2/SDL_render.h>
#include <stdbool.h>

typedef struct Image {
  // Loaded texture
  SDL_Texture *texture;

  // Original width and height
  int w, h;

  // Current coordinates, width and height
  SDL_Rect rect;
} Image;

bool Image_load(SDL_Renderer *renderer, Image *image, const char *file);
void Image_destroy(Image *image);

void Image_render(SDL_Renderer *renderer, Image *image);
void Image_renderCrop(SDL_Renderer *renderer, Image *image, SDL_Rect *crop,
                      SDL_Point *pos);

inline bool Image_load(SDL_Renderer *renderer, Image *image, const char *file) {
  image->texture = IMG_LoadTexture(renderer, file);
  if (!image->texture) {
    fprintf(stderr,
            "Unable to load image '%s'\n"
            "SDL_image Error: %s\n",
            file, IMG_GetError());
    return false;
  }

  SDL_QueryTexture(image->texture, NULL, NULL, &image->w, &image->h);

  image->rect.w = image->w;
  image->rect.h = image->h;

  return true;
}

inline void Image_destroy(Image *image) {
  SDL_DestroyTexture(image->texture);
  memset(image, 0, sizeof(Image));
}

inline void Image_render(SDL_Renderer *renderer, Image *image) {
  SDL_RenderCopy(renderer, image->texture, NULL, &image->rect);
}

inline void Image_renderCrop(SDL_Renderer *renderer, Image *image, SDL_Rect *crop,
                      SDL_Point *pos) {
  SDL_Rect rect = image->rect;
  rect.w = crop->w;
  rect.h = crop->h;

  if (pos) {
    rect.x = pos->x;
    rect.y = pos->y;
  }

  SDL_RenderCopy(renderer, image->texture, crop, &rect);
}

#endif // header file protect
